`timescale 1ns / 1ps
//////////////////////////////////////////////////////////////////////////////////
// Company: 
// Engineer: 
// 
// Create Date:    20:13:04 05/01/2014 
// Design Name: 
// Module Name:    enemy 
// Project Name: 
// Target Devices: 
// Tool versions: 
// Description: 
//
// Dependencies: 
//
// Revision: 
// Revision 0.01 - File Created
// Additional Comments: 
//
//////////////////////////////////////////////////////////////////////////////////
module enemy(	walk_en, Xsprite, Ysprite,
					blank,hcount,vcount,clk,rst,
					tile_address,sprite);

	input clk,rst,walk_en,blank;
	input [10:0] hcount,vcount;
	input [9:0] Xsprite, Ysprite;
	output	sprite;
	output [11:0] tile_address;

	parameter 	DELAY = 25;
	

	reg [4:0]	frame_delay;
	reg [11:0] 	tile_address;
	reg [1:0]	next_frame;


	initial begin
		next_frame <= 0;
		frame_delay <=0;
		tile_address <= 0;
	end

	always @ (posedge clk) begin
		if (rst) begin
			next_frame <= 0;
			frame_delay <=0;
			tile_address <= 0;
		end
		
		if ( Ysprite == 0 ) begin
				tile_address <= 0;
		end
		
		else if (sprite) begin
			
			tile_address <= tile_address + 1'b1;
			
			// ------- animation frame selection --------
   		case (next_frame)
			0: begin
					if (tile_address == (1024*1)-1) begin 
						if (frame_delay >= DELAY) begin
							frame_delay <= 0;
							next_frame <= 1;
						end
						else begin
							tile_address <= 0;
							frame_delay <= frame_delay + 1'b1;
						end
					end
				end
			1: begin
					if (tile_address == (1024*2)-1) begin
						if (frame_delay >= DELAY) begin
							frame_delay <= 0;
							next_frame <= 2;
						end
						else begin
							tile_address <= 1024;
							frame_delay <= frame_delay + 1'b1;
						end
					end
				end
			2: begin
					if (tile_address == (1024*3)-1) begin
						if (frame_delay >= DELAY) begin
							frame_delay <= 0;
							next_frame <= 3;
							tile_address <= 1024;
						end
						else begin
							tile_address <= 1024*2;
							frame_delay <= frame_delay + 1'b1;
						end
					end
				end
			3: begin
					if (tile_address == (1024*2)-1) begin
						if (frame_delay >= DELAY) begin
							frame_delay <= 0;
							next_frame <= 0;
							tile_address <= 0;
						end
						else begin
							tile_address <= 1024;
							frame_delay <= frame_delay + 1'b1;
						end
					end
				end
			default: begin
					if (tile_address == (1024*1)-1) begin 
						if (frame_delay >= DELAY) begin
							frame_delay <= 0;
							next_frame <= 1;
						end
						else begin
							tile_address <= 0;
							frame_delay <= frame_delay + 1'b1;
						end
					end
				end
			endcase
		end		
	end

	assign sprite = ~blank & (hcount >= Xsprite & hcount <= Xsprite+31 & vcount >= Ysprite & vcount <= Ysprite+31);

endmodule
